import { ref } from 'vue'
import { message } from 'ant-design-vue'
import type { UploadProps, UploadChangeParam } from 'ant-design-vue'
import pdfjsLib from 'pdfjs-dist';
export const useUploadFile = () => {
  const fileList = ref<UploadProps['fileList']>([])
  const uploadLoading = ref(false)
  const beforeUpload: UploadProps['beforeUpload'] = async (file) => {
    console.log('file0', file)
    const isPdf = file.type === 'application/pdf'
    if (!isPdf) {
      console.log('You can only upload PDF file!', uploadLoading.value)
      message.warn('只能上传PDF文件')
      return false
    }

    const isLt20M = file.size / 1024 / 1024 < 20
    if (!isLt20M) {
      console.log('File must smaller than 20MB!', uploadLoading.value)
      message.warn('文件大小不能超过20M')
      return false
    }
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.onload = async (e) => {
        try {
          const arrayBuffer = e.target.result;
          const loadingTask = window.pdfjsLib.getDocument(arrayBuffer);
          const pdf = await loadingTask.promise;
          const numPages = pdf.numPages;

          if (numPages > 50) {
            message.warn('PDF 页数超过 50 页，无法上传');
            reject();
          } else {
            resolve();
          }
        } catch (error) {
          message.warn('读取 PDF 文件失败');
          reject();
        }
      };
      reader.onerror = () => {
        message.warn('读取 PDF 文件失败');
        reject();
      };
      reader.readAsArrayBuffer(file);
    });
  }
  const handleChange = (info: UploadChangeParam) => {
    console.log('info', info)
  }
  const uploadLoadingChange = (loading: boolean) => {
    uploadLoading.value = loading
  }
  return {
    fileList,
    beforeUpload,
    handleChange,
    uploadLoading,
    uploadLoadingChange
  }
}
